package com.gz.mylife.app;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.im.FirstEnterAppTagDao;
import com.gz.mylife.im.SessionBean;
import com.gz.mylife.im.SessionDao;
import com.gz.mylife.util.UdpReceiver;
import com.igexin.sdk.PushManager;
import com.zl.smartmall.library.ISmartMall;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.listener.AdvertiseListener;
import com.zl.smartmall.library.po.AdvertInfopic;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.ShareUtil;

public class SplashScreen extends Activity {
	private static AdvertiseListener advertiselistener;
	// 图片的地址，这里可以从服务器获取
	public static List<String> urllist = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash_screen);
		UdpReceiver.startreciver(SplashScreen.this);
		urllist.clear();
		init();//加载缓存图片
		initListener();
		PushManager.getInstance().initialize(this.getApplicationContext());

		// 创建本地文件夹，用来存放广告页面的图片
		createSDCardDir();
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (IAuth.getInstance().loadCookieStore() != null) {
					startActivity(new Intent(getApplicationContext(),
							AdvertisementActivity.class));// 进入App的广告页
				} else {
					startActivity(new Intent(getApplicationContext(),
							Login.class));// 未登录进入登录页面
				}
				finish();
			}
		}, 2000);

		if (IAuth.getInstance().loadCookieStore() != null) {
			new LoadCommunityManager(getApplicationContext()).getCommunitys();

			List<SessionBean> mDataList = SessionDao.findSessionFirstByLimit(
					getApplicationContext(), 0);
			boolean isFirst = FirstEnterAppTagDao
					.isFirst(getApplicationContext());
			if (mDataList.size() > 0 || isFirst) {
				int unReadCount = 0;
				for (int i = 0; i < mDataList.size(); i++) {
					SessionBean bean = mDataList.get(i);
					unReadCount += bean.getUnreadCount();
				}
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT,
						unReadCount);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.splash_screen, menu);
		return true;
	}

	/**
	 * 在SD卡上创建文件夹
	 * 
	 * @param context
	 * @param dirName
	 * @return
	 */
	public void createSDCardDir() {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			// 创建一个文件夹对象，赋值为外部存储器的目录
			File sdcardDir = Environment.getExternalStorageDirectory();
			// 得到一个路径，内容是sdcard的文件夹路径和名字
			String path = sdcardDir.getPath() + "/com.gz.mylife";
			File path1 = new File(path);
			if (!path1.exists()) {
				// 若不存在，创建目录，可以在应用启动的时候创建
				path1.mkdirs();
				setTitle("paht ok,path:" + path);
			}
		} else {
			setTitle("false");
			return;

		}

	}
	//加载缓存图片(一直都是加载缓存图片)
	public void init(){
		String jsonobject = ShareUtil.getstringvalue(getApplicationContext(), "advertiseImg");
		if (jsonobject==null ||jsonobject=="") {
			onLoadingAdvertise();
		}else{
			try {
				JSONObject object = new JSONObject(jsonobject);
				JSONArray listArray = object.getJSONArray("list");
				for (int i = 0; i < listArray.length(); i++) {
					JSONObject advertise = listArray.getJSONObject(i);
					urllist.add(object.getString("images_host")+advertise.getString("ad_pic"));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 获取广告图片
	 */
	public static void onLoadingAdvertise() {
		// TODO Auto-generated method stub
		ISmartMall.getInstance().getAdvertise(advertiselistener);
	}

	public void initListener() {

		advertiselistener = new AdvertiseListener() {
			@Override
			public void onNoMoreData() {
				// TODO Auto-generated method stub

			}

			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				Toast.makeText(SplashScreen.this, Define.MSG_NO_NETWORK, Toast.LENGTH_LONG).show();
				init();
			}

			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				//您已处于离线状态
				Toast.makeText(SplashScreen.this, Define.MSG_OFFLINE_ERROR, Toast.LENGTH_LONG).show();
			}

			@Override
			public void onResponseFailed() {
				// TODO Auto-generated method stub
				init();
			}

			@Override
			public void onResponseSuccess(List<AdvertInfopic> advertInfos,String json) {
				// TODO Auto-generated method stub
				urllist.clear();
				ShareUtil.setstringvalue(getApplicationContext(), "advertiseImg", json);
				for (int i = 0; i < advertInfos.size(); i++) {
					urllist.add(advertInfos.get(i).getPicture());
				}

			}

		};
	}
}
